from datetime import datetime
import datetime
from flask import request, jsonify, current_app, g, abort

from ihome import db
from ihome.models import Order, House
from ihome.modules.api import api_blu
from ihome.utils.common import user_login_data
from ihome.utils.response_code import RET, error_map


# 添加订单
@api_blu.route('/orders', methods=["POST", "GET", "PUT"])
@user_login_data
def orders():
    # 判断用户是否登陆
    user = g.user
    if not user:
        return abort(403)

    # 添加订单
    if request.method == "POST":
        # 获取参数
        house_id = request.json.get('house_id')
        start_date = request.json.get('start_date')
        end_date = request.json.get('end_date')
        # 校验参数
        if not all([house_id, start_date, end_date]):
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

        try:
            house_id = int(house_id)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

        # 计算居住天数
        start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
        end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        delta = end_date - start_date
        days = delta.days
        # 根据house_id查询house的数据
        try:
            house = House.query.get(house_id)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
        house_price = house.price
        # 数据库操作,添加订单的信息
        order = Order()
        order.house_id = house_id
        order.begin_date = start_date
        order.end_date = end_date
        order.house_price = house_price
        order.user_id = user.id
        order.days = days
        order.amount = days * house_price
        db.session.add(order)

        try:
            db.session.commit()
        except BaseException as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

        data = {
            "order_id": order.id
        }

        return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)

    # 获取订单列表
    if request.method == "GET":
        # 获取参数
        role = request.args.get("role")
        # 校验参数
        if role not in ["custom", "landlord"]:
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

        orders = []

        # 判断是房东还是房客
        if role == "custom": # 房客 我的订单
            print("custom")

            orders_f = Order.query.filter(Order.user_id == user.id).order_by(Order.create_time.desc()).all()

            orders = [order.to_dict() for order in orders_f]

        if role == "landlord": # 房东 客户的订单
            my_houses = user.houses
            my_houses_id_list = [house.id for house in my_houses]
            my_houses_orders = Order.query.filter(Order.house_id.in_(my_houses_id_list) ).all()

            orders = [order.to_dict() for order in my_houses_orders]
        print(orders)


            # print("landlord")
            # my_houses = House.query.filter(House.user_id == user.id).all()
            # print(my_houses) # [<House 13>, <House 14>, <House 15>, <House 16>, <House 17>, <House 18>]
            # # zxzx = [house.id for house in my_houses]
            # my_houses_id_list = []
            # for house in my_houses:
            #     if int(house.id):
            #         my_houses_id_list.append(house.id)
            # print(my_houses_id_list) # [13, 14, 15, 16, 17, 18]
            # for my_houses_id in my_houses_id_list:
            #     print(my_houses_id)
            #     my_houses_orders = Order.query.filter(Order.house_id == my_houses_id).all()
            #     print(my_houses_orders)
            #     orders = [order.to_dict() for order in my_houses_orders]
            #     print(orders)

        data = {
            "orders": orders
        }
        print(data)
        return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)

    # 接单和拒单
    if request.method == "PUT":
        # 获取参数
        action = request.json.get("action")
        order_id = request.json.get("order_id")
        reason = request.json.get("reason")

        # 校验参数
        if not all([action, order_id]):
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        if action not in ["accept", "reject"]:
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        try:
            order_id = int(order_id)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        try:
            order = Order.query.get(order_id)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
        # accept
        if action == "accept":
            order.status = "PAID"
        if action == "reject":
            if not reason:
                return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
            order.statu = "REJECTED"
            order.comment = reason
        return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 评论订单
@api_blu.route('/orders/comment', methods=["PUT"])
@user_login_data
def orders_comment():
    # 判断用户是否登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 获取参数
    comment = request.json.get("comment")
    order_id = request.json.get("order_id")
    # 校验参数
    if not all([comment, order_id]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        order = Order.query.get(order_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    order.comment = comment
    order.status = "COMPLETE"

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
